from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q

from app.controllers.appointment.space import appointment_space_controller
from app.controllers.marketing.coupons import coupons_controller
from app.controllers.marketing.coupons_rule import coupons_rule_controller
from app.controllers.saas.pay import pay_controller
from app.controllers.system.user import user_controller
from app.schemas.saas import PayCreate
from app.settings import settings
from app.controllers.customer.users import users_controller
from app.controllers.orders.list import orders_list_controller
from app.models import OrdersList, Coupons, CouponsRole, User, CustomerUser
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.orders import *
from app.core.dependency import DependCustomerAuth
from app.core.ctx import CTX_USER_ID
from datetime import datetime

mini_saas_pay_router = APIRouter()

@mini_saas_pay_router.get("/list", summary=f"查看会员列表", dependencies=[DependCustomerAuth])
async def list_customer(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description="姓名/手机号"),
):
    q = Q()
    if name:
        q &= (Q(name__contains=name) | Q(phone__contains=name))
    total, customer_objs = await users_controller.list(page=page, page_size=page_size, search=q, order=["card_no"] ,filed=["parent"])
    data = [await obj.to_dict(m2m=True,exclude_fields=["password"]) for obj in customer_objs]
    level_objs = await users_controller.level_list()
    for item in data:
        item["role_name"] = level_objs.get(item["role_id"], None)
        item["parent"] = item["parent_id"]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@mini_saas_pay_router.get("/get", summary="查看会员详情")
async def get_customer(
        id: int = Query(..., description="会员id"),
):
    api_obj = await users_controller.get_detail(user_id=id)
    data = await api_obj.to_dict()
    return Success(data=data)



@mini_saas_pay_router.post("/create", summary=f"创建订单", dependencies=[DependCustomerAuth])
async def do_orders_list_create(
        data_in: PayCreate,
):
    add_uid = CTX_USER_ID.get()

    if add_uid:
        ret = await pay_controller.do_creat(data_in=data_in, add_uid=add_uid)
        if ret["pay_status"] == 1:
            return Success(msg="下单成功", data=ret)
        else:
            return Fail(msg=ret["msg"])
    else:
        return Fail(msg="请使用员工账号下单")

@mini_saas_pay_router.get("/coupons_list", summary=f"客户优惠券列表", dependencies=[DependCustomerAuth])
async def do_coupons_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        user_id: int = Query(0, description=f"用户id"),
):
    q = Q(is_used=0,user_id=user_id)
    total, data = await coupons_controller.do_list(page=page, page_size=page_size, search=q)
    type_objs = await coupons_rule_controller.level_list()
    for item in data:
        item['type_name'] = type_objs[item['coupons_id']]

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@mini_saas_pay_router.get("/saas_orders", summary=f"查看所有用户订单列表")
async def do_orders_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        user_name: str = Query(None, description=f"下单人名称"),
        status: int = Query(0, description="订单状态"),
        start_time: str = Query("", description="开始时间"),
        end_time: str = Query("", description="结束时间"),
        is_express: int = Query(-1, description="发货状态"),
        type: int = Query(-1, description="订单类型"),
        type2: int = Query(1, description="1当前2历史"),
):
    search_user_ids = []
    if user_name:
        search_users = await CustomerUser.filter(name__contains=user_name).values("id")
        search_user_ids = {orders['id'] for orders in search_users}  # 获取所有的 user_id
    q = Q(type__in=[2,3,4])
    today_start = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
    # 根据 type2 参数来查询今天的订单或今天之前的订单
    if type2 == 1:  # 今天的订单
        q &= Q(created_at__gte=today_start)  # created_at >= 今天零点
    elif type2 == 2:  # 今天之前的订单
        q &= Q(created_at__lt=today_start)  # created_at < 今天零点
    if status:
        q &= Q(status=status)
    if is_express > -1:
        q &= Q(is_express=is_express)
    if type>-1:
        q &= Q(type=type)
    if user_name:
        q &= Q(user_id__in=search_user_ids)
    if start_time and end_time:
        q &= Q(pay_time__range=[start_time, end_time])
    elif start_time:
        q &= Q(pay_time__gte=start_time)
    elif end_time:
        q &= Q(pay_time__lte=end_time)
    total, data = await orders_list_controller.do_list(page=page, page_size=page_size, search=q)
    user_ids = {orders['user_id'] for orders in data}  # 获取所有的 user_id
    users = await CustomerUser.filter(id__in=user_ids)
    users_dict = {user.id: user for user in users}
    space_objs = await appointment_space_controller.level_list()
    for orders in data:
        user = users_dict.get(orders['user_id'])
        if user:
            orders['user_name'] = user.name
            orders['user_phone'] = user.phone  # 设置一个默认值
        else:
            orders['user_name'] = "用户已被删除"  # 设置一个默认值
            orders['user_phone'] = ""  # 设置一个默认值
        orders['status_name'] = settings.ORDERS_STATUS[orders['status']]
        orders['express_name'] = settings.EXPRESS_STATUS[orders['is_express']]
        if orders['address_id']>0:
            orders['address_name'] = space_objs[orders['address_id']]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)
